<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12">
        <v-form ref="postAddForm" v-model="valid" lazy-validation>
          <!--标题-->
          <v-text-field v-model="post.title" :rules="titleRules" outlined label="标题" clearable></v-text-field>
          <!--摘要-->
          <v-text-field v-model="post.desc" :rules="descRules" outlined label="摘要" clearable></v-text-field>
          <div id="editor">
            <p v-html="post.content"></p>
          </div>
          <br/>
          <!--提交按钮-->
          <v-btn :disabled="!valid" color="primary" class="mr-4" v-on:click="validate">提交</v-btn>
          <!--清空按钮-->
          <v-btn color="default" class="mr-4" @click="editor.txt.clear()">清空</v-btn>
        </v-form>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import E from 'wangeditor'

export default {
  name: 'PostEdit',
  data: () => ({
    editor: null,
    valid: true,
    post: {
      title: '',
      desc: '',
      content: ''
    },
    titleRules: [
      v => !!v || '请输入标题',
      v => (v.length >= 1 && v.length <= 20) || '标题不得超过40个字符'
    ],
    descRules: [
      v => !!v || '请输入摘要',
      v => (v.length >= 1 && v.length <= 50) || '摘要不得超过100个字符'
    ]
  }),
  methods: {
    validate () {
      const valid = this.$refs.postAddForm.validate()
      if (valid) {
        this.$axios.patch('api/post/' + this.$route.params.id + '/', {
          title: this.post.title,
          desc: this.post.desc,
          content: this.editor.txt.html()
        }).then(response => {
          console.log(response)
        }).catch(error => {
          console.log(error)
        })
      }
    }
  },
  mounted () {
    // 首先发送请求获取对应的帖子
    this.$axios.get('api/post/' + this.$route.params.id + '/')
      .then(response => {
        console.log(response)
        this.post = response.data
        this.editor = new E('#editor')
        // 启用本地图片上传
        this.editor.customConfig.uploadImgShowBase64 = true
        this.editor.create()
        this.editor.txt.html(this.post.content)
      }).catch(error => {
        console.log(error)
      })
  }
}
</script>

<style scoped>

</style>
